package com.hyjiacan.tools.apps.dbm.services

import java.sql.Connection
import java.time.Instant
import java.util.*

object MysqlConnections {
    private val connections: MutableMap<String, ConnectionInfo> = mutableMapOf()

    private val timer: Timer = Timer()

    init {
        // 每2分钟执行一次
        val interval = 2 * 60 * 1000L
        timer.scheduleAtFixedRate(TaskTool(), 0, interval)
    }

    fun get(name: String): Connection? {
        if (!connections.containsKey(name)) {
            return null
        }
        var connection = connections[name]?.connection
        if (connection != null && connection.isClosed) {
            connections.remove(name)
            connection = null
        }
        return connection
    }

    fun set(name: String, connection: Connection) {
        if (connections.containsKey(name)) {
            connections[name]!!.updateTime()
        } else {
            connections[name] = ConnectionInfo(connection)
        }
    }

    class ConnectionInfo(val connection: Connection) {
        var lastAccessTime: Long = 0

        init {
            lastAccessTime = Instant.now().epochSecond
        }

        fun updateTime() {
            lastAccessTime = Instant.now().epochSecond
        }
    }

    class TaskTool : TimerTask() {
        override fun run() {
            val expiredConnections = mutableListOf<String>()
            val now = Instant.now().epochSecond
            // 距离最后一次访问，允许继续存活时长
            // 5 分钟
            val aliveTime = 5 * 60
            connections.forEach { (t, info) ->
                if ((now - info.lastAccessTime) >= aliveTime) {
                    expiredConnections.add(t)
                }
            }
            // 移除连接
            expiredConnections.forEach { name ->
                println("Connection $name has been idle for 5 minutes, close it.")
                val info = connections.remove(name)!!
                info.connection.close()
            }
        }

    }
}